package com.bai.test;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by Admin on 12/19 0019.
 */

public class DaoImp<T> implements DAO<T> {
    private Class<T> clazz;
    private QueryRunner queryRunner = new QueryRunner();

    public DaoImp(){
        Type superClass=getClass().getGenericSuperclass();
        if(superClass instanceof ParameterizedType){
            ParameterizedType type= (ParameterizedType) superClass;
            Type[] types=type.getActualTypeArguments();
            if(types !=null && types.length>0){
                if(types[0] instanceof Class){
                    clazz= (Class<T>) types[0];
                }
            }
        }
    }

    @Override
    public void update(String sql, Object... args) {
        Connection connection=null;
        try{
            connection=JDBCTools.getConnection();
            queryRunner.update(connection,sql,args);
        }catch (Exception e){
            e.printStackTrace();
        }finally{
            JDBCTools.release(null,null,connection);
        }
    }

    @Override
    public T get(Connection connection,String sql, Object...args) {

        try {
            return queryRunner.query(connection,sql,new BeanHandler<>(clazz),args);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<T> getList(String sql, Object...args) {
        Connection connection=null;
        List<T> list=null;
        try{
            connection=JDBCTools.getConnection();
            list=queryRunner.query(connection,sql,new BeanListHandler<>(clazz),args);

        }catch (Exception e){
            e.printStackTrace();
        }finally{
            JDBCTools.release(null,null,connection);
        }
        return list;
    }

    @Override
    public <E> E getForValue(String sql, Object... args) {
        Connection connection=null;
        try{
            connection=JDBCTools.getConnection();
          return(E) queryRunner.query(connection,sql,new ScalarHandler(),args);
        }catch (Exception e){
            e.printStackTrace();
        }finally{
            JDBCTools.release(null,null,connection);
        }
        return null;
    }
}
